﻿// <copyright file="ExpressionHelper.cs" company="DataAbstractor">
//   (c) Luke Geraghty 2013
// </copyright>
// <summary>
//   The expression helper.
// </summary>

namespace DataAbstractor
{
    using System.Linq.Expressions;

    /// <summary>
    /// The expression helper.
    /// </summary>
    public static class ExpressionHelper
    {
        /// <summary>
        /// Get the property name from an expression.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <returns>The property name as a string.</returns>
        public static string GetPropertyName(Expression expression)
        {
            var lambdaExpression = expression as LambdaExpression;
            if (lambdaExpression != null)
            {
                expression = lambdaExpression.Body;
            }

            var memberExpression = expression as MemberExpression;
            if (memberExpression != null)
            {
                return memberExpression.Member.Name;
            }

            var unaryExpression = expression as UnaryExpression;
            if (unaryExpression == null)
            {
                return null;
            }

            memberExpression = unaryExpression.Operand as MemberExpression;
            return memberExpression == null ? null : memberExpression.Member.Name;
        }
    }
}
